import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/character_count_text_field.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/modules/lifeCircle/data/repository/life_repository_impl.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 举报页面
@RoutePage()
class LifeReportScreen extends ConsumerStatefulWidget {
  final String topicId;

  const LifeReportScreen({super.key, required this.topicId});

  @override
  ConsumerState<LifeReportScreen> createState() => _LifeReportScreenState();
}

class _LifeReportScreenState extends ConsumerState<LifeReportScreen> {
  int? _selectedReportType; // 0-广告骚扰 1-盗图侵权 2-人身攻击 3-色情低俗 4-违法违规 5-涉嫌诈骗 6-其他
  final TextEditingController _reportReasonController = TextEditingController();
  bool _isSubmitting = false;

  // 举报类型列表（写死的）
  final List<Map<String, dynamic>> _reportTypes = [
    {'type': 0, 'text': '广告骚扰'},
    {'type': 1, 'text': '盗图侵权'},
    {'type': 2, 'text': '人身攻击'},
    {'type': 3, 'text': '色情低俗'},
    {'type': 4, 'text': '违法违规'},
    {'type': 5, 'text': '涉嫌诈骗'},
    {'type': 6, 'text': '其他'},
  ];

  @override
  void dispose() {
    _reportReasonController.dispose();
    super.dispose();
  }

  /// 提交举报
  Future<void> _handleSubmit() async {
    if (_selectedReportType == null) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请选择举报原因')));
      }
      return;
    }

    // 如果选择"其他"，必须填写原因
    if (_selectedReportType == 6 &&
        _reportReasonController.text.trim().isEmpty) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请填写举报原因')));
      }
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

    try {
      final repository = LifeRepositoryImpl(
        apiClient: ref.read(apiClientProvider),
      );

      final reportTypeInfo = _reportTypes.firstWhere(
        (element) => element['type'] == _selectedReportType,
      );
      await repository.reportTopic(
        topicId: widget.topicId,
        reportType: _selectedReportType.toString(),
        reportReason: _selectedReportType == 6
            ? _reportReasonController.text.trim()
            : (reportTypeInfo['text'] as String? ?? ""),
      );

      if (mounted) {
        // 提交成功后，关闭页面，返回到详情页面
        Navigator.of(context).pop();
      }
    } catch (e) {
      debugPrint("举报失败: $e");
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('举报失败: ${e.toString()}')));
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(title: '举报'),
      body: Stack(
        children: [
          Column(
            children: [
              // 举报选项列表（包含输入框）
              Expanded(
                child: ListView.builder(
                  padding: EdgeInsets.only(
                    left: 16.w,
                    right: 16.w,
                    top: 8.h,
                    bottom: 8.h,
                  ),
                  itemCount:
                      _reportTypes.length +
                      (_selectedReportType == 6 ? 1 : 0), // 如果选择了"其他"，增加一项用于输入框
                  itemBuilder: (context, index) {
                    // 如果是最后一项且选择了"其他"，显示输入框
                    if (_selectedReportType == 6 &&
                        index == _reportTypes.length) {
                      return Padding(
                        padding: EdgeInsets.only(
                          top: 36.h, // 距离"其他"选项 36.h
                        ),
                        child: CharacterCountTextField(
                          controller: _reportReasonController,
                          hintText: '详细描述下您的举报内容',
                          maxLength: 140,
                          maxLines: 5,
                          showDoneAction: true,
                        ),
                      );
                    }

                    // 普通列表项
                    final reportType = _reportTypes[index];
                    final type = reportType['type'] as int;
                    final text = reportType['text'] as String;
                    final isSelected = _selectedReportType == type;

                    return Column(
                      children: [
                        InkWell(
                          onTap: () {
                            setState(() {
                              _selectedReportType = type;
                            });
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(vertical: 16.h),
                            child: Row(
                              children: [
                                // 单选按钮
                                Container(
                                  width: 20.w,
                                  height: 20.w,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: isSelected
                                          ? context.colorScheme.primary
                                          : (context
                                                    .customColorThemeNonNull
                                                    .gray2 ??
                                                Colors.grey.shade300),
                                      width: 2,
                                    ),
                                    color: isSelected
                                        ? context.colorScheme.primary
                                        : Colors.transparent,
                                  ),
                                  child: isSelected
                                      ? Icon(
                                          Icons.check,
                                          size: 14.w,
                                          color: Colors.white,
                                        )
                                      : null,
                                ),
                                SizedBox(width: 12.w),
                                // 文本
                                Expanded(
                                  child: Text(
                                    text,
                                    style: context.textTheme.bodyMedium
                                        ?.copyWith(
                                          color: context
                                              .customColorThemeNonNull
                                              .textColor1,
                                        ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        // 分割线
                        Divider(
                          height: 1,
                          thickness: 1,
                          color:
                              context.customColorThemeNonNull.gray1 ??
                              Colors.grey.shade200,
                        ),
                      ],
                    );
                  },
                ),
              ),

              // 提交按钮
              PrimaryButton(
                text: "提交",
                width: 200.w,
                height: 40.h,
                onPressed: _handleSubmit,
              ),
              SizedBox(height: 16.h),
            ],
          ),

          // Loading遮罩
          if (_isSubmitting)
            Container(
              color: Colors.black.withValues(alpha: 0.3),
              child: const Center(child: CircularProgressIndicator()),
            ),
        ],
      ),
    );
  }
}
